package samsung.sds.departmentManagement.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import samsung.sds.departmentManagement.model.DepartmentEntity;
import samsung.sds.departmentManagement.service.DepartmentManagementService;
import samsung.sds.system.common.baseQuery.model.PageData;
import samsung.sds.system.common.model.QueryParam;
import samsung.sds.system.utils.CommonTools;
import samsung.sds.system.utils.Constants;
import samsung.sds.userManagement.model.UserEntity;
import samsung.sds.userManagement.service.UserManagementService;

/**
 * @author wch.wu
 * @createDate 2016-01-15
 *
 * 组织机构管理控制器
 */
@Controller
@RequestMapping("/departmentManagement")
public class DepartmentManagementController {

	@Autowired
	private DepartmentManagementService departmentManagementServiceImpl;
	
	@Autowired
	private UserManagementService userManagementServiceImpl;
	
	/**
	 * 跳转到组织机构页面
	 */
	@RequestMapping(value="/departmentList",method = RequestMethod.POST)
	public String departmentList(){		
		return "/departmentManagement/departmentList";
	}
	
	/**
	 * 查询所有组织机构（数据量较小所以全部查找出，然后在页面上展示隐藏）
	 */
	@RequestMapping(value="/queryDepartments",method = RequestMethod.POST)
	@ResponseBody
	public List<DepartmentEntity> queryDepartments() {	
		List<DepartmentEntity> departmentEntitys = new ArrayList<DepartmentEntity>();
		QueryParam param = new QueryParam();
		departmentEntitys = departmentManagementServiceImpl.queryList(param);
		return departmentEntitys;
	}
	
	/**
	 * 新建组织机构
	 */
	@RequestMapping(value="/insertDepartment",method = RequestMethod.POST)
	@ResponseBody
	public String insertDepartment(DepartmentEntity departmentEntity) {
		// 获取数据库已经存在的最大组织机构deptId，在此基础上加1
		String deptId = CommonTools.getKeyUUID();
		departmentEntity.setDeptId(deptId);
		
		// 插入新的组织机构节点、如果新插入的组织机构节点是第一个子节点则把父节点以前的用户移动到这个节点下
		int count = departmentManagementServiceImpl.insertEntity( departmentEntity );
		if( count == 1 ){
			return Constants.SUCCESS_CODE;
		}else{
			return Constants.FAILURE_CODE;
		}
	}
	
	/**
	 * 修改组织机构
	 */
	@RequestMapping(value="/updateDepartment",method = RequestMethod.POST)
	@ResponseBody
	public String updateDepartment(DepartmentEntity departmentEntity) {
		
		int count = departmentManagementServiceImpl.updateEntity( departmentEntity );
		if( count == 1 ){
			return Constants.SUCCESS_CODE;
		}else{
			return Constants.FAILURE_CODE;
		}
	}

	/**
	 * 删除组织机构
	 * @param request
	 */
	@RequestMapping(value="/deleteDepartment",method = RequestMethod.POST)
	@ResponseBody
	public String deleteDepartment(HttpServletRequest request) {
		DepartmentEntity departmentEntity = new DepartmentEntity();
		String deptId = new String(request.getParameter("deptId"));
		departmentEntity.setDeptId(deptId);
		
		// 查询节点本身信息和所有后代节点信息
		List<DepartmentEntity> departmentEntities = departmentManagementServiceImpl.queryDepartmentList(deptId);
		
		// 判断所有叶子节点是否存在用户（如果count大于0，代表这个节点下存在用户，那么这个节点不可以删除）
		int count = userManagementServiceImpl.queryDepartmentUserCount(departmentEntities);
		if( count <= 0 ){
			// 删除这个组织机构和所有后代组织机构、修改父节点状态
			int deleteCount = departmentManagementServiceImpl.deleteEntitys(departmentEntities, deptId);
			if( deleteCount > 0 ){
				return Constants.SUCCESS_CODE;
			}else{
				return Constants.FAILURE_CODE;
			}
		} else {
			return Constants.FAILURE_CODE;
		}
	}

	/**
	 * 向组织机构增加用户
	 * @param request
	 * @return 
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/addUserForDepartment",method = RequestMethod.POST)
	@ResponseBody
	public String addUserForDepartment(HttpServletRequest request) throws UnsupportedEncodingException {
		String deptId = new String( request.getParameter("deptId") );
		String userNameStr = request.getParameter("userNames");
		String temUserName = URLDecoder.decode(userNameStr, "UTF-8");
		String[] userNames = temUserName.split(",");
		int i =userManagementServiceImpl.updateUser(deptId, userNames);
		if(i >= 0)
			return Constants.SUCCESS_CODE;
		else
			return Constants.FAILURE_CODE;
	}
	
	/**
	 * 从组织机构中删除用户
	 * @param request
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/removeUserFromDepartment",method = RequestMethod.POST)
	@ResponseBody
	public String removeUserFromDepartment(HttpServletRequest request) throws UnsupportedEncodingException {
		
		// 从组织机构中移除用户
		String deptId = new String( "-1" );
		String userNameStr = request.getParameter("userNames");
		String temUserName = URLDecoder.decode(userNameStr, "UTF-8");
		String[] userNames = temUserName.split(",");
		
		int removeCount = userManagementServiceImpl.updateUser(deptId, userNames);
		if( removeCount > 0 ){
			return Constants.SUCCESS_CODE;
		}else{
			return Constants.FAILURE_CODE;
		}
	}
	
	/**
	 * 查找所有用户（调用用户表分页接口）
	 * @param request
	 */
	@RequestMapping(value="/queryAllUsers",method = RequestMethod.POST)
	@ResponseBody
	public PageData<UserEntity> queryAllUsers(HttpServletRequest request){
		
		QueryParam param = CommonTools.getQueryParam(request);
		return departmentManagementServiceImpl.queryDepartmentUsersListPage(param );
	}
	
	/**
	 * 查找已经加入到这个组织机构下面的所有用户（调用用户表分页接口）
	 * @param request
	 */
	@RequestMapping(value="/queryUsersInDepartment",method = RequestMethod.POST)
	@ResponseBody
	public PageData<UserEntity> queryUsersInDepartment(HttpServletRequest request){
		QueryParam param = CommonTools.getQueryParam(request);
		return departmentManagementServiceImpl.queryDepartmentUsersListPage(param );
	}
	
	/**
	 * 弹出用户查询窗口
	 */
	@RequestMapping(value="/addUser_sitemesh_popup",method = RequestMethod.GET)
	public String deptUserSelectPopup(){		
		return "/departmentManagement/deptUserSelectPopup";
	}
	
	/**
	 * 组织机构新增（或修改）服务器端验证
	 * 		修改组织机构：验证相同父组织机构的兄弟组织机构名称是否重复
	 * 		新建组织机构：根据组织机构名和父组织机构deptId判断同名节点是否存在
	 * @throws IOException
	 */
	@RequestMapping(value="/departmentValidate",method = RequestMethod.POST)
	@ResponseBody
	public boolean departmentValidate(DepartmentEntity tmpDepartmentEntity) throws IOException{
		
		// 返回验证结果标记
		boolean validateResult = true;
		
		// 查询是否已经存在相同数据
		DepartmentEntity departmentEntity = departmentManagementServiceImpl.findUniqueByProperty( tmpDepartmentEntity );
		if( null != departmentEntity ){
			
			// 用户名已经存在
			validateResult = false;
		}
		return validateResult;
	}
	
}
